<?php

namespace App\Http\Controllers\Site;

use App\Http\Controllers\Controller;
use App\Models\Site;
use App\User;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;

class adminController extends Controller
{

    public function index(Site $site)
    {
        return view('admin.index', compact('site'));
    }

    public function search(Request $request)
    {
        if ($name = $request->name) {
            $users = User::Search($name)->limit(10)->get();
        } else {
            $users = User::limit(10)->get();
        }

        return $users;
    }

    public function add(Request $request, Site $site, User $user)
    {
//        if(!$site->admins->contains($user)){
//            $site->admins()->attach([$user['id']]);
//        }
        $site->admins()->syncWithoutDetaching([$user['id']]);
        return back()->with('success', '管理员设置成功');

    }


    public function edit($id)
    {
        //
    }


    public function update(Request $request, $id)
    {
        //
    }


    public function destroy(Site $site, User $admin)
    {

//管理员删除时，同时删除数据库中的角色
        $site->roles->map(function ($role) use ($admin) {
            $admin->removeRole($role['name']);
        });

        $site->admins()->detach([$admin['id']]);
        return response()->json(['message' => '删除成功']);

    }

    public function role(Site $site, User $user)
    {
        return view('admin.role', compact('site', 'user'));
    }

    public function roleUpdate(Request $request, Site $site, User $user)
    {

        //删除无效的旧角色
        $site->roles->filter(function ($role) use ($request) {

            return !in_array($role['id'], $request->input('roles') ?? []);
        })->map(function ($role) use ($user) {
            $user->removeRole($role['name']);
        });

        //分配新角色
        $user->assignRole($request->roles);

        return back()->with('success', '角色设置成功');
    }
}
